package com.issac.messagequeue.mqserver.coreclass;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.issac.messagequeue.mqserver.common.ConsumerEnv;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 一个存储消息的队列
 */
@Data
public class MSGQueue {
    private String name;
    private boolean durable = false;
    // exclusive: true-只能被一个消费者使用；false-所有消费者都能使用（TODO：暂未实现）
    private boolean exclusive = false;
    private boolean autoDelete = false;
    // 扩展参数（TODO：暂未实现）
    private Map<String, Object> arguments = new HashMap<>();
    // 消费者列表：有哪些消费者订阅了当前队列
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();

    // 记录当前取到第几个消费者
    private AtomicInteger consumerSeq = new AtomicInteger(0);

    public void addConsumerEnv(ConsumerEnv consumerEnv) {
        consumerEnvList.add(consumerEnv);
    }

    public ConsumerEnv chooseConsumer() {
        if (consumerEnvList.size() == 0) {
            return null;
        }
        // 计算当前要取的元素下标
        int index = consumerSeq.get() % consumerEnvList.size();
        consumerSeq.getAndIncrement();  // 实现轮流切换消费者
        return consumerEnvList.get(index);
    }

    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<HashMap<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    // 以下代码供测试使用
    public Object getArguments(String key) {
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }

}
